package com.slt.concurrency.mashibing2019.juc.c_007_LockAndTools;


import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * countdownlatch ： 倒数 门栓
 * 当倒数到0时候，门栓打开
 */
public class T06_TestCountDownLatch {
    public static void main(String[] args) {
//        usingJoin();
        usingCountDownLatch();
    }

    private static void usingCountDownLatch() {
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);

        for(int i=0; i<threads.length; i++) {
            threads[i] = new Thread(()->{
                try {
                    Thread.sleep(new Random().nextInt(9000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
                latch.countDown();
            });
        }
        //启动所有的线程
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        new Thread(()->{
            try {
                //有 await这个线程，会检查所有 countdown的线程已经执行完毕，他才能执行。
                latch.await();
                System.out.println("end latch");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private static void usingJoin() {
        Thread[] threads = new Thread[100];

        for(int i=0; i<threads.length; i++) {
            threads[i] = new Thread(()->{
                int result = 0;
                for(int j=0; j<10000; j++)
                    result += j;
            });
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }

        for (int i = 0; i < threads.length; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("end join");
    }
}
